var createError = require('http-errors');
var express = require('express');
var path = require('path');
var multer = require('multer');
var cookieSession = require('cookie-session');
var logger = require('morgan');
let cors = require("cors");


// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));


app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));

// multer的配置
let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (req.url.includes('reg')) {
      cb(null, path.join(__dirname, 'public', 'upload', 'user'))
    } else if (req.url.includes('banner')) {
      cb(null, path.join(__dirname, 'public', 'upload', 'banner'))
    } else {
      cb(null, path.join(__dirname, 'public', 'upload', 'product'))
    }
  }
})


let upload = multer({
  storage
});
app.use(upload.any());

app.use(cookieSession({
  name: 'huashuo',
  keys: ['aa', 'bb', 'cc'],
  maxAge: 1000 * 60 * 60 * 24
}))

app.use(cors({
  //允许所有前端域名
  "origin": ["http://127.0.0.1:8054"],
  "credentials": true, //允许携带凭证
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  //被允许的提交方式
  "allowedHeaders": ['Content-Type', 'Authorization'] //被允许的post方式的请求头
}));

//资源托管
app.use(express.static(path.join(__dirname, 'public', 'template')));
app.use('/admin', express.static(path.join(__dirname, 'public', 'admin')));
app.use(express.static(path.join(__dirname, 'public')));


//客户端
// let jwt = require("./utils/jwt");
app.use('/api/login', require('./routes/api/login'))
app.use('/api/reg', require('./routes/api/reg'))

// app.all('/api/*', require('./routes/api/params'))
app.use('/api/user', require('./routes/api/user'))

// app.use('/api/home', require('./routes/api/home'))

// app.use('/api/follow', require('./routes/api/follow'))
// app.use('/api/column', require('./routes/api/column'))
app.use('/api/list', require('./routes/api/list'))


//短信验证接口
app.use('/message/send-code', require('./routes/message/send-code'))

// let open = require("./utils/mgdb").open
// let bcrypt = require("./utils/bvrypt")
// app.all("/api/*", require("./routes/api/params"));
// console.log(0);
// app.get("/api/test", (req, res, next) => {
//   console.log(1);
//   // console.log('query', req.query)
//   // console.log('body', req.body)
//   // console.log('files', req.files)
//   // console.log('session', req.session)
//   // res.send({
//   //   a: 1,
//   //   b: 2
//   // })
//   // 开库
//   // open({
//   //   collectionName: 'list'
//   // }).then(res => console.log(res))
//   // 查询列表
//   // findList({}).then(res => console.log(res)).catch(err => console.log(err))
//   // 查询详情
//   // findDetail({
//   //   _id: "5fcf5e0a1bba29f06f7beb9a"
//   // }).then(res => console.log(res)).catch(err => console.log(err))
//   // jwt
//   // let token = jwt.sigin({
//   //   username: 'apple',
//   //   _id: '5fcf5e0a1bba29f06f7beba1'
//   // })
//   // console.log(1, token);
//   // jwt.verift(token).then(res => console.log(2, res)).catch(err => console.log(3, err))
//   // 加盐
// let hash = bcrypt.hash('app123');
// console.log(1, hash); //入库
// //   // // 解密 
// let result = bcrypt.compare('alex123', '$2b$10$ChklUa1qChmSMnDjK/V2puWV/if4Z1yxszveCZ2fySKMfkmomjf/C')
// console.log(2, result); //true 通过
//   // console.log(req.query._page, req.body._limit, req.headers._sort, req.query.q)
//   console.log(req.token)
// })


//管理端
app.use('/admin', require('./routes/admin/index'));
app.use('/admin/users', require('./routes/admin/users'));
app.use('/admin/banner', require('./routes/admin/banner-json'));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// 代理端
app.use("/proxy/home", require("./routes/proxy/home"));

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  if (req.url.includes('/api')) {
    res.send({
      err: 1,
      msg: '张越鑫真帅'
    })
  } else if (req.url.includes('/admin')) {
    res.render('error'); //后端渲染了错误页面
  } else {
    res.sendFile(path.join(__dirname, 'public', 'template', '404.html'))
  }
});

module.exports = app;